package com.ynwa.nio.jenkov;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author gzd
 * @date 2017/12/25 17:09
 * @desc 翻译nio教程，第4章buffer示例
 */
public class FileBufferDemo {

    public static void main(String[] args) throws IOException {
        RandomAccessFile aFile = new RandomAccessFile("/Users/kopshome/buffer.txt", "rw");
        FileChannel inChannel = aFile.getChannel();

        // 创建buffer，capacity 设置为 48 bytes
        ByteBuffer buf = ByteBuffer.allocate(48);

        int bytesRead = inChannel.read(buf); // 读取至buffer.
        while (bytesRead != -1) {

            buf.flip();  // 让buffer做好读取的准备

            while (buf.hasRemaining()) {
                System.out.print((char) buf.get()); // 每次读取1 byte
            }

            buf.clear(); //让buffer做好写入的准备
            bytesRead = inChannel.read(buf);
        }
        aFile.close();
    }
}
